﻿using CaptchaGen;
using LuShanTea.Common;
using LuShanTea.Front.Web.Models;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LuShanTea.Front.Web.Controllers
{
    public class LoginController : Controller
    {
        /// <summary>
        /// 验证码
        /// </summary>
        public const string CODE = "CODE";
        /// <summary>
        /// 用户Id
        /// </summary>
        public const string USERID = "USERID";

        /// <summary>
        /// 发给哪个邮箱
        /// </summary>
        public const string GetBackPWdEmail = "GetBackPWdEmail";
        /// <summary>
        /// 发个邮箱的验证码
        /// </summary>
        public const string EMAILCODE = "EMAILCODE";
        /// <summary>
        /// 是否通过验证
        /// </summary>
        public const string ISVALID = "ISVALID";

        public IUserService UserService { get; set; }
        // GET: Login
        [HttpGet]
        public ActionResult Index()
        {
            if (Session[USERID]!=null)
            {
                return Redirect("/Home/Index");
            }
            return View();
        }
        [HttpPost]
        public ActionResult Index(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) });
            }
            string code = (string)TempData[CODE];
            if (code != model.Code)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "验证码错误" });
            }
            var user = UserService.GetByEmailOrPhoneNum(model.UserName, model.UserName);
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "账户或密码错误" });
            }
            if (UserService.CheckIsLock(user.Id))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "您的帐户已被锁定，请在" + (user.LoginErrorTime.AddMinutes(30)-DateTime.Now ).Minutes + "分钟后在试" });
            }

            if (!UserService.CheckLogin(model.UserName, model.Password))
            {
                UserService.LockUser(user.Id);
                return Json(new AjaxResult { Status = "error", ErrorMsg = "账号或密码错误" });
            }
            UserService.UnLockUser(user.Id);
            Session[USERID] = user.Id;
            return Json(new AjaxResult { Status = "ok" });
        }

        public ActionResult GetValidCode()
        {
            string res;
            string code = CommonHelper.CreateVerifyCode(out res);
            TempData[CODE] = res;
            Stream ms = ImageFactory.GenerateImage(code, 40, 150, 12, 2);
            return File(ms, "image/jpeg");
        }

        [HttpGet]
        public ActionResult GetBackPwd1()
        {
            return View();
        }
        [HttpPost]
        public ActionResult GetBackPwd1(GetBackPwdFirstModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) });
            }

            //发送验证码
            return Json(SendEmailCode(model));
        }

        public AjaxResult SendEmailCode(GetBackPwdFirstModel model)
        {
            string code = (string)TempData[CODE];
            if (code == null)
            {
                return new AjaxResult { Status = "error", ErrorMsg = "验证码已过期" };
            }
            if (code != model.Code)
            {
                return new AjaxResult { Status = "error", ErrorMsg = "验证码错误，请刷新" };
            }
            if (UserService.GetByEmail(model.Email) == null)
            {
                return new AjaxResult { Status = "error", ErrorMsg = "邮箱不存在" };
            }

            //获取要给邮箱发送的验证码
            string emailCode = CommonHelper.GetPhoneValidCode();
            //记录验证码
            TempData[EMAILCODE] = emailCode;
            //保存邮箱
            Session[GetBackPWdEmail] = model.Email;

            TempData[ISVALID] = null;

            LuShanEmailSms sms = new LuShanEmailSms();
            sms.Code = emailCode;
            sms.Email = model.Email;
            return sms.Send();
        }


        [HttpGet]
        public ActionResult GetBackPwd2()
        {
            string email = (string)Session[GetBackPWdEmail];
            if (email == null)
            {
                return Redirect("/Login/GetBackPwd1");
            }
            return View((object)email);
        }

        [HttpPost]
        public ActionResult GetBackPwd2(string EmailCode)
        {
            if (EmailCode == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "验证码不能为空" });
            }
            string email = (string)Session[GetBackPWdEmail];
            if (email == null)
            {
                return Json(new AjaxResult { Status = "redirect", Data = "/Login/GetBackPwd1" });
            }
            string serverEmailCode = (string)TempData[EMAILCODE];
            Session[EMAILCODE] = null;
            if (serverEmailCode != EmailCode)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "验证码错误，请重新获取" });
            }
            TempData[ISVALID] = true;
            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpGet]
        public ActionResult GetBackPwd3()
        {
            string email = (string)Session[GetBackPWdEmail];
            if (email == null)
            {
                return Redirect("/Login/GetBackPwd1");
            }
            return View((object)email);
        }

        [HttpPost]
        public ActionResult GetBackPwd3(GetBackPwd3Model model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) });
            }
            if (TempData[ISVALID] == null)
            {
                return Json(new AjaxResult { Status = "redirect", ErrorMsg = "您没有通过第二步的验证", Data = "/Login/GetBackPwd2" });
            }
            string email = (string)Session[GetBackPWdEmail];
            //清除session
            Session[GetBackPWdEmail] = null;
            if (email == null)
            {
                return Json(new AjaxResult { Status = "redirect", Data = "/Login/GetBackPwd1" });
            }
            if (email != model.Email)
            {
                return Json(new AjaxResult { Status = "redirect", ErrorMsg = "表单已过期", Data = "/Login/GetBackPwd2" });
            }
            var user = UserService.GetByEmail(email);
            if (user == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "邮箱不存在" });
            }
            UserService.RetrievePwd(user.Id, model.newPassWord);
            return Json(new AjaxResult { Status = "ok" });
        }

        public ActionResult GetBackPwd4()
        {
            return View();
        }

        [HttpPost]
        public ActionResult IsLogin()
        {
            if (Session[USERID] == null)
            {
                return Json(new AjaxResult { Status = "no" });
            }
            long id = (long)Session[USERID];
            var user = UserService.GetById(id);
            if (user==null)
            {
                Session[USERID] = null;
                return Json(new AjaxResult { Status = "no" });
            }
            return Json(new AjaxResult { Status = "yes",Data=user.NiceName });
        }
    }
}